
#include <stdio.h>

#include <map>
#include <vector>
#include "ttds_test.hpp"

namespace ct{

std::vector<c_test*> *g_alltests_ptr;
void c_test_cleanup(void)
{
    if (g_alltests_ptr){
        delete g_alltests_ptr;
        g_alltests_ptr = NULL;
    }
}

void c_test::add(c_test *ptr)
{
    if (!g_alltests_ptr){
        g_alltests_ptr = new std::vector<c_test*>();
        g_alltests_ptr->reserve( 64 );
    }

    g_alltests_ptr->push_back(ptr);
}

struct test_result
{
    std::string name;
    std::string msg;
    bool pass = false;
};

void c_test_run_all(void)
{
    if (g_alltests_ptr){
        int pass = 0;
        int failed = 0;
        std::map<std::string,test_result> results;
        for (auto ptr:*g_alltests_ptr){
            test_result r;
            r.name = ptr->name;
            try {
                printf("\033[32mRUNNING %s\033[0m\n", ptr->name.c_str() );
                ptr->main();
                if (ptr->failed == 0){
                    printf("\033[32mRUNNING %s OK\033[0m SUCESS:%d\n", ptr->name.c_str(), ptr->success );
                } else {
                    printf("\n\033[31mRUNNING %s FAILED\033[0m SUCCESS:%d FAILED:%d\n", ptr->name.c_str(), ptr->success, ptr->failed );
                }
                r.msg = "";
                r.pass = true;
            }catch (std::exception &e){
                r.msg = e.what();
                printf("\033[31mRUNNING %s FAILED.\033[0m\n", ptr->name.c_str() );
                r.pass = false;
            } catch( ct::exception &e){
                r.msg = e.msg;
                printf("\033[31mRUNNING %s FAILED: %s\033[0m\n", ptr->name.c_str(), r.msg.c_str() );
                r.pass = false;
            } catch (...){
                printf("\033[31mRUNNING %s FAILED.\033[0m\n", ptr->name.c_str() );
                r.msg = "unkown exception";
                r.pass = false;
            }
            pass += ptr->success;
            failed  += ptr->failed;
            results[r.name] = r;
        }

        printf("\n\033[32m TOTAL checked pass:%d failed:%d total:%d\033[0m\n\ndone\n", pass, failed, (pass+failed) );
    }
}

}